import { Breadcrumb, Button, Table, Space, Cascader, Modal, DatePicker, message, TableProps, Row, Col } from 'antd';
import React, { FC } from 'react';
import { FormPanel, type FormPanelObject, FormPanelBtnAlign, InputType, Utils } from 'lfun-bg-comp';
import { useNavigate } from 'react-router-dom';
import _ from 'lodash';
import { PageContainer } from '@/component/page-container';
import { GENDER, YES_NO } from '@/constant/basicOptions';
import { PAGINATIONCONFIG } from '@/constant/page';
import { STU_CHANGE_TYPE } from '@/constant/studentOptions';
import utils, { getPathRoot } from '@/utils';
import { TNewStudents } from '@/service/student/types';
import { StuNewStudentSrv } from '@/service/student';
import SearchInput from '@/view/component/searchInput';
import { searchSchoolByName } from '@/service/unit/school';
import { exportStuInfo, innerTransaction } from '@/service/student/instudent';
import { getGradeClassOptions } from '@/service/options';
import styles from './index.less';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';
import useCountry from '@/hooks/useCountry';

const Groups: FC = () => {
  //const [search, setSearch] = React.useState('');
  const [value, setValue] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(10);
  const [pageIndex, setPageIndex] = React.useState(1);
  const [showChangeModel, setShowChangeModel] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [curFormPanelObject, setCurFormPanelObject] = React.useState<any>();
  //const [curForm, setCurForm] = React.useState<any>();
  const country = useCountry();

  const [cur, setCur] = React.useState<any>();
  const isSchool = Utils.getProps('isSchool');

  const pageChange = (pageIndex, pageSize) => {
    searchFunc(curFormPanelObject.getFieldsValue(), pageIndex, pageSize);
  };

  const searchFunc = async (params, pageIndex, pageSize) => {
    setLoading(true);
    const param: TNewStudents.TReqNewStudentsParams = {
      ...params,
      approval_status: 'assignment',
      page: pageIndex,
      per_page: pageSize,
    };
    // if (params.enrollment_date) {
    //   param.enrollment_date = params.enrollment_date.format('YYYY-MM-DD');
    // }
    const r = await StuNewStudentSrv.list(param);
    if (r.success) {
      setValue(r?.data?.items || []);
      setTotal(r?.data?.total || 0);
      setPageIndex(pageIndex);
      setPageSize(pageSize);
    } else if (curFormPanelObject) {
      curFormPanelObject.reVaildation(r);
    }
    setLoading(false);
  };

  React.useEffect(() => {
    searchFunc({}, pageIndex, pageSize);
  }, []);

  const navigate = useNavigate();
  const { RangePicker } = DatePicker;

  const handleView = record => {
    navigate(`${getPathRoot()}/instudent/details/${record.student_id}`, { state: { ...record } });
  };
  const handleEdit = record => {
    setCur(record);
    setShowChangeModel(true);
  };

  const columns: TableProps['columns'] = [
    {
      title: '姓名',
      dataIndex: 'student_name',
      key: 'student_name',
      fixed: 'left',
      width: 100,
    },
    {
      title: '界别',
      dataIndex: 'session',
      key: 'session',
    },
    {
      title: '学籍号',
      dataIndex: 'edu_number',
      key: 'edu_number',
    },
    {
      title: '性别',
      dataIndex: 'student_gender',
      key: 'student_gender',
      render(v, record, index) {
        return _.find(GENDER, { value: v })?.label;
      },
    },
    {
      title: '区县',
      dataIndex: 'block',
      key: 'block',
      render: (text: any) => {
        return _.find(country, { value: String(text) })?.label;
      },
    },
    {
      title: '学校名称',
      dataIndex: 'school_name',
      key: 'school_name',
    },
    {
      title: '年级班级',
      dataIndex: 'class_name',
      key: 'class_name',
      render: (text, record) => {
        return `${record.grade_name || ''} ${record.class_name ? `${record.class_name}班` : ''}`;
      },
    },
    {
      title: '入学时间',
      dataIndex: 'enrollment_date',
      key: 'enrollment_date',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      fixed: 'right',
      //width: 200,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          <PermissionButton permission="current_student_view">
            <Button type="link" onClick={() => handleView(record)}>
              查看
            </Button>
          </PermissionButton>
          {isSchool && (
            <PermissionButton permission="change">
              <Button type="link" onClick={() => handleEdit(record)}>
                异动
              </Button>
            </PermissionButton>
          )}
        </Space>
      ),
    },
  ];

  const list = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '学籍号',
          name: 'studentId',
          key: 'studentId',
        },
        {
          label: '学校名称',
          name: 'school_id',
          key: 'school_id',
          inputType: InputType.children,
          relationFields: ['class_id'],
          children: (
            <SearchInput
              onLoadOption={null}
              searchFunction={async v => {
                const res = await searchSchoolByName(v, 1, 100);
                if (res.success) {
                  return res.data.map(item => ({
                    label: item.school_name,
                    value: item.id,
                  }));
                }
                return [];
              }}
              randerOption={option => option}
            />
          ),
        },
        {
          label: '年级班级',
          name: 'class_id',
          key: 'class_id',
          inputType: InputType.children,
          children: <Cascader />,
          renderOption: async (form, values) => {
            const res = await getGradeClassOptions(form);
            return res;
          },
          formatSubmitValue: values => {
            if (values && values.length && values.length === 2) return values[1];
            return null;
          },
        },
        {
          label: '姓名',
          name: 'student_name',
          key: 'student_name',
        },
        {
          label: '性别',
          name: 'student_gender',
          key: 'student_gender',
          inputType: InputType.select,
          renderOption: GENDER,
        },
        {
          label: '临时就读',
          name: 'emporary_borrowing_status',
          key: 'emporary_borrowing_status',
          inputType: InputType.select,
          renderOption: YES_NO,
        },
        {
          label: '区县',
          name: 'county',
          key: 'county',
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '入学时间',
          name: 'enrollment_date_range',
          key: 'enrollment_date_range',
          inputType: InputType.children,
          children: <RangePicker />,
          formatSubmitValue: values => {
            if (values && values.length)
              return values
                .map(val => {
                  if (val && val.isValid && val.isValid()) {
                    return val.format('YYYY-MM-DD');
                  }
                  return val;
                })
                .join(',');
            return values;
          },
        },
      ],
    },
  ];
  const changeList = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      span: 24,
      inputs: [
        {
          label: '姓名',
          name: 'student_name',
          key: 'student_name',
          required: true,
        },
        {
          label: '异动类别',
          name: 'transaction_type',
          key: 'transaction_type',
          inputType: InputType.children,
          children: <Cascader />,
          required: true,
          renderOption: STU_CHANGE_TYPE,
        },
        {
          label: '异动原因',
          name: 'transaction_reason',
          key: 'transaction_reason',
          inputType: InputType.textarea,
        },
      ],
    },
  ];
  const buildBtns = () => {
    return [
      <PermissionButton permission="export">
        <Button
          type="primary"
          onClick={async () => {
            const res = await exportStuInfo(curFormPanelObject.getFieldsValue());
            if (res.success) {
              message.success('导出操作成功,请耐心等待完成,去任务管理下载!');
              return;
            }
            message.error(`导出操作失败,${res.message || res.detail}`);
          }}
        >
          导出
        </Button>
      </PermissionButton>,
    ];
  };
  return (
    <PageContainer header={<Breadcrumb items={[{ title: '在校生信息管理' }]} />}>
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        restBtnText="重置"
        submitBtnText="查询"
        buttons={buildBtns()}
        onLoad={(formPanelObject: FormPanelObject) => {
          setCurFormPanelObject(formPanelObject);
        }}
        onFinish={(formPanelObject: FormPanelObject) => {
          const vals = formPanelObject.getFieldsValue();
          // const v = {
          //   ...vals,
          //   // class_id: vals.class_id && vals.class_id.length > 0 ? vals.class_id[1] : 0,
          //   // enrollment_date_range:
          //   //   vals.enrollment_date_range && vals.enrollment_date_range.length > 0
          //   //     ? vals.enrollment_date_range.join(',')
          //   //     : '',
          // };
          searchFunc(vals, 1, pageSize);
        }}
        template={list}
      />
      <Row className={styles.extend_btns}>
        {isSchool && (
          <PermissionButton permission="start_in">
            <Button
              type="primary"
              onClick={() => navigate(`${getPathRoot()}/instudent/checkin`)}
              style={{ marginRight: '15px' }}
            >
              发起转入
            </Button>
          </PermissionButton>
        )}

        {isSchool && (
          <PermissionButton permission="start_out">
            <Button type="primary" onClick={() => navigate(`${getPathRoot()}/instudent/checkout`)}>
              发起转出
            </Button>
          </PermissionButton>
        )}
      </Row>
      <Table
        dataSource={value}
        columns={columns}
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <Modal title="异动" open={showChangeModel} onCancel={() => setShowChangeModel(false)} footer={null}>
        <FormPanel
          btnsAlign={FormPanelBtnAlign.center}
          restBtnText="取消"
          submitBtnText="确定"
          onReset={() => setShowChangeModel(false)}
          values={cur}
          onFinish={async (formPanelObject: FormPanelObject) => {
            const vals = formPanelObject.getFieldsValue();
            const params = {
              ...vals,
              student_id: cur.student_id,
              transaction_type: vals.transaction_type.join(','),
            };
            const r = await innerTransaction(params);
            if (r.success) {
              message.success('操作成功');
              setShowChangeModel(false);
              searchFunc({}, 1, pageSize);
            } else {
              formPanelObject.reVaildation(r);
            }
            return r.success;
          }}
          template={changeList}
        />
      </Modal>
    </PageContainer>
  );
};

export default Groups;
